'''
    Import Module
    
    Loads common 3D formats
'''

from models import Model, VBOMesh

def LoadXModel(path, scale = 1.0, swizzler = lambda set: [set[0], set[2], -set[1]], n_flips = None, **kwargs):
    '''
        Loads the .x format into a VBO mesh. Simplified.
        
        TODO:
            - load the matrix
            - load things like TexCoords
    '''
    
    def blockRead(tag, size, index = None, preprocessor = lambda x: x):
        line = f.readline()
        while line and line.find(tag) == -1: 
            line = f.readline()
        
        if not line: return None, None
        
        # read in vertices
        lib = []
        array = []
        i = int(f.readline()[:-2])
        for x in xrange(i):
            set = preprocessor(map(float, f.readline().split(';')[:size]))
            lib.append(set)
            
        
        if index is None:
            # read in index and assemble array
            index = []
            i = int(f.readline()[:-2])
            for x in xrange(i):
                index_set = map(int, f.readline().split(';')[1].split(','))
                index.append(index_set)
                array.extend([lib[j] for j in index_set])
        else:
            # use given index
            for index_set in index:
                array.extend([lib[j] for j in index_set])
        return array, index
    
    f = open(path, 'r')
    
    vert_pp_w = lambda x: [i * scale for i in swizzler(x)]
    norm_pp = swizzler if n_flips is None else lambda x: [i*j for i,j in zip(swizzler(x), n_flips)]
    
    
    vertices, v_index = blockRead('Mesh {', 3, preprocessor = vert_pp_w)
    normals, n_index = blockRead('MeshNormals {', 3, preprocessor = norm_pp)
    textureCoords, t_index = blockRead('MeshTextureCoords {', 2, v_index)
    
    # retutn Model
    return Model(mesh = VBOMesh(vertices, normals, textureCoords, **kwargs), **kwargs)
    